package admin.models;

import helpers.GeneralHelper;
import helpers.NumberHelper;
import helpers.StringHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.cache.Cache;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

import debugs.CategoryDebug;

import entities.Category;

public class CategoryModel {
	
	private Objectify ofy;

	private Cache cache = null;

	private String cachePrefix = "category_";

	private static CategoryModel instance = null;
	
	public static CategoryModel getInstance() {
		if (instance == null) {
			instance = new CategoryModel();
		}
		
		return instance;
	}
	
	private CategoryModel() {
		try {
			ObjectifyService.register(Category.class);
		} catch (Exception e) {
			// e.printStackTrace();
		}
		cache = GeneralHelper.getCache();
		ofy = GeneralHelper.getObjectify();
	}

	public List<Category> list(int limit, int page) {
		List<Category> categories = new ArrayList<Category>();

		int start = (page - 1) * limit;
		categories = ofy.query(Category.class).order("order").limit(limit)
				.offset(start).list();
		
		return categories;
	}
	
	public void insert(Category category) {
		//Set parents and level
		String parents = "";
		
		if (!category.getParentId().isEmpty()) {
			Category parentCategory = getCategory(category.getParentId());
			if (parentCategory != null) {
				parents = parentCategory.getParents();
				int level = parentCategory.getLevel() + 1;
				category.setParents(parents);
				category.setLevel(level);
				
			}
		}
		
		if (!category.getParentId().isEmpty()) {
			parents += "," +  category.getId();
		} else {
			parents += category.getId();
		}
		category.setParents(parents);
		
		if (category.getOrder().isEmpty()) {
			//Get Order
			String order = getNextOrder(category.getParentId(), category.getLevel());
			category.setOrder(order);
		}
		
		ofy.put(category);
		
	}

	public void update(Category category) {
		ofy.put(category);
	}
	
	public void delete(Category category) {
		ofy.delete(category);
	}
	
	public List<Category> listByParentCategory(String parentId, int limit, int page) {
		List<Category> categories = new ArrayList<Category>();
		
		int start = (page - 1) * limit;
		categories = ofy.query(Category.class).filter("parentId", parentId).order("order").limit(limit).offset(start).list();
		
		if (categories == null) {
			categories = new ArrayList<Category>();
		}
		
		return categories;
	}
	
	public List<Category> listNotContainCategory(String id) {
		List<Category> categories = new ArrayList<Category>();
		
		categories = ofy.query(Category.class).order("order").list();
		
		if (categories == null) {
			categories = new ArrayList<Category>();
		}
		
		return categories;
	}
	
	public List<Category> listWithLevel(int level) {
		List<Category> categories = new ArrayList<Category>();
		
		categories = ofy.query(Category.class).filter("level <=", level).list();
		
		if (categories == null) {
			categories = new ArrayList<Category>();
		}
		
		//Sort category
		Collections.sort(categories, new Comparator<Category>(){
            public int compare(Category o1, Category o2) {
            	Category c1 = (Category) o1;
            	Category c2 = (Category) o2;
               return c1.getOrder().compareToIgnoreCase(c2.getOrder());
            }
        });
		
		return categories;
	}
	
	public List<Category> listParents(String id) {
		List<Category> parents = new ArrayList<Category>();
		Category category = getCategory(id);
		if (category != null) {
			String[] ids = category.getParents().split(",");
			for (int i = 0; i < ids.length; i++) {
				if (!ids[i].isEmpty()) {
					category = getCategory(ids[i]);
					if (category != null) {
						parents.add(category);
					}
				}
			}
		}
		
		return parents;
	}
	
	public List<Category> listChildren(String parent) {
		
		List<Category> categories  = ofy.query(Category.class).filter("parentId", parent).order("order").list();
		
		if (categories == null) {
			categories = new ArrayList<Category>();
		}
		
		return categories;
	}
	
	public boolean hasChildren(String id) {
		boolean hasChildren = false;
		Category category = ofy.query(Category.class).filter("parentId", id).get();
		if (category != null) {
			hasChildren = true;
		} else {
			category = getCategory(id);
			if (category != null && category.getCount() > 0) {
				hasChildren = true;
			}
		}
		
		return hasChildren;
	}
	
	public Category getCategory(String id) {
		
		Category category = new Category();
		
		try {
			category = ofy.get(new Key<Category>(Category.class, id));
		} catch (Exception e) {
			category = null;
		}
		
		return category;
	}
	
	public Map<String, Category> getByListId(List<String> ids) {
		Map<String, Category> categories = new TreeMap<String, Category>();
		
		try {
			categories = ofy.get(Category.class, ids);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
		return categories;
	}
	
	public List<Category> getListId(List<String> ids) {
		List<Category> categories = new ArrayList<Category>();
		
		Map<String, Category> ars = getByListId(ids);
		
		for (Map.Entry<String, Category> entry : ars.entrySet()) {
			if (entry.getValue() != null) {
				categories.add(entry.getValue());
			}
		}
		
		return categories;
	}
	
	public List<Category> getAll() {
		List<Category> categories = new ArrayList<Category>();
		
		categories = ofy.query(Category.class).order("order").list();
		
		if (categories == null) {
			categories = new ArrayList<Category>();
		}
		
		return categories;
	}
	
	public Map<String, Category> getMapAll() {
		
		Map<String, Category> categories = new TreeMap<String, Category>();
		
		List<Category> c = getAll();
		
		for (int i = 0; i < c.size(); i++) {
			if (c.get(i) != null) {
				categories.put(c.get(i).getId(), c.get(i));
			}
		}	

		return categories;
	}
	
	public int count() {
		int n  = ofy.query(Category.class).count();
		return n;
	}
	
	public String getNextOrder(String parent, int level) {
		String next = "";
		
		//Get parent category
		Category p = getCategory(parent);
		if (p != null) {
			next = p.getOrder();
		}
		
		//Get near category children
		Category category = null;
		try {
			category = ofy.query(Category.class).filter("parentId", parent).filter("level", level).order("-order").get();
		} catch (Exception e) {
			// TODO: handle exception
		}

		if (category != null) {
			int stt = NumberHelper.StringToInt(category.getOrder()) + 1;
			next = NumberHelper.IntToString(stt);
		} else {
			next = next + "A";
		}
		
		return next;
	}
	
	public void updateOrder(String id, String order) {
		Category category = getCategory(id);
		
		if (category != null && !category.getOrder().equalsIgnoreCase(order)) {
			category.setOrder(order);
			update(category);
		}
		
		//Update children
		if (hasChildren(id)) {
			List<Category> childs = listChildren(id);
			
			for (int i = 0; i < childs.size(); i++) {
				String o = order + NumberHelper.IntToString(i + 1);
				updateOrder(childs.get(i).getId(), o);
			}
			
		}
	}
	
	public void reUpdateAllOrder() {
		List<Category> categories = listChildren("");
		
		String order = "";
		for (int i = 0; i < categories.size(); i++) {
			String o = order + NumberHelper.IntToString(i + 1);
			updateOrder(categories.get(i).getId(), o);
		}
	}
	
	public void reUpdateOrder(List<String> ids) {
		List<Category> categories = getListId(ids);
		
		if (categories.size() > 0) {
			
			String order = "";
			
			for (int i = 0; i < categories.get(0).getLevel(); i++) {
				order += "A";
			}
			
			int n = NumberHelper.StringToInt(order);
			
			for (int i = 0; i < categories.size(); i++) {
				String o = NumberHelper.IntToString(n + i);
				updateOrder(categories.get(i).getId(), o);
			}
		}
	}
}
